<template>
  <div class="house-management">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/sys/houseManagement?navIndex=3' }">数据中心</el-breadcrumb-item>
      <el-breadcrumb-item
        :to="{ path: '/sys/houseManagement?navIndex=3' }"
        v-if="dtype!='list'"
        @click.native="dtype='list'"
      >房屋管理</el-breadcrumb-item>
      <el-breadcrumb-item v-if="dtype=='list'">房屋管理</el-breadcrumb-item>
      <el-breadcrumb-item v-if="dtype=='add'">添加房屋</el-breadcrumb-item>
      <el-breadcrumb-item v-if="dtype=='edit'">编辑房屋</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row class="el-margin-v-30 el-padding-l-25 el-padding-r-40">
      <el-row class="el-padding-20 el-white-bgcolor">
        <el-row v-show="dtype==='list'">
          <el-row>
            <el-col :span="2" style="min-width:120px;">
              <el-button type="primary" size="small" @click="routeTo('add')">添加房屋</el-button>
            </el-col>
            <el-col :span="3">
              <el-input
                size="small"
                class="el-margin-r-10"
                placeholder="请输入楼栋号"
                prefix-icon="el-icon-search"
                v-model="buildNum"
                :clearable="true"
                @change="search"
              ></el-input>
            </el-col>
            <el-col :span="3" style="margin-left:10px;">
              <el-input
                size="small"
                class="el-margin-r-10"
                placeholder="请输入楼单元"
                prefix-icon="el-icon-search"
                v-model="unitNum"
                :clearable="true"
                @change="search"
              ></el-input>
            </el-col>
            <el-col :span="3" style="margin-left:10px;">
              <el-input
                size="small"
                class="el-margin-r-10"
                placeholder="请输入楼房号"
                prefix-icon="el-icon-search"
                v-model="houseNum"
                :clearable="true"
                @change="search"
              ></el-input>
            </el-col>
            <el-col :span="3" style="margin-left:10px;">
              <el-select v-model="isAuth" placeholder="请选择认证信息" size="small" @change="search" clearable>
                <el-option label="未认证" :value="0"></el-option>
                <el-option label="已认证" :value="1"></el-option>
              </el-select>
            </el-col>
            <div style="float:right">
              <button class="el-btn-file">
                <input
                  ref="referenceUpload"
                  type="file"
                  @change="upload($event)"
                  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                />
                <span>excel导入</span>
              </button>
              <el-button size="small" @click="download">下载excel</el-button>
            </div>
            <!-- <el-col :span="6">
                <el-button type="primary" size="small" @click="routeTo('add')">添加房屋</el-button>
                el-upload
                  :action="action"
                  :data="cur"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  multiple
                  :limit="3"
                  :on-exceed="handleExceed"
                  :file-list="fileList">
                  <el-button size="small" type="success">点击上传</el-button>
                </el-upload
                <button class="el-btn-file">
                  <input type="file" @change="upload($event.target.files)" accept="application/vnd.ms-excel"/>
                  <span>excel导入</span>
                </button>
                <el-button size="small" @click="download">下载excel</el-button>
            </el-col>-->
            <!-- <el-col :span="18" class="el-align-right el-font-xs">
                楼栋：
                <el-input
                  class="el-margin-r-10"
                  placeholder="请输入楼栋号"
                  prefix-icon="el-icon-search"
                  v-model="buildNum"
                  style="width:130px;"
                  @change="search">
                </el-input>
                单元：
                <el-input
                  class="el-margin-r-10"
                  placeholder="请输入楼单元"
                  prefix-icon="el-icon-search"
                  v-model="unitNum"
                  style="width:130px;"
                  @change="search">
                </el-input>
                房号：
                <el-input
                  class="el-margin-r-10"
                  placeholder="请输入楼房号"
                  prefix-icon="el-icon-search"
                  v-model="houseNum"
                  style="width:130px;"
                   @change="search">
                </el-input>
                是否认证：
                <el-select v-model="isAuth" placeholder="请选择认证信息" style="width:120px;" @change="search">
                  <el-option label="全部" value="all"></el-option>
                  <el-option label="否" :value="0"></el-option>
                  <el-option label="是" :value="1"></el-option>
                </el-select>
            </el-col>-->
          </el-row>
          <el-table
            class="el-margin-t-10"
            :data="table.tableData"
            border
            stripe
            style="width:100%"
            size="small"
            :highlight-current-row="true"
            ref="multipleTable"
          >
            <el-table-column label="楼栋" prop="buildNum" width="180"></el-table-column>
            <el-table-column label="单元" prop="unitNum" width="180"></el-table-column>
            <el-table-column label="房号" prop="houseNum" width="180"></el-table-column>
            <el-table-column label="销售面积(平方米)" prop="saleArea" width="180"></el-table-column>
            <el-table-column label="实际面积(平方米)" prop="realArea" width="180"></el-table-column>
            <el-table-column label="房屋类型" prop="houseType">
              <template slot-scope="scope">{{houseTypes[scope.row.houseType-1]}}</template>
            </el-table-column>
            <el-table-column label="业主认证" prop="isAuth" width="180">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.isAuth?'success':'warning'"
                  effect="light"
                >{{scope.row.isAuth?'已认证':'未认证'}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="是否可用" prop="usable">
              <template slot-scope="scope">{{scope.row.usable?"是":"否"}}</template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime" width="180">
              <template slot-scope="scope">{{scope.row.createTime}}</template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button type="text" @click="routeTo('edit',scope.row)">编辑</el-button>
                <el-button type="text" @click="setUsable(scope.row)">{{scope.row.usable?"禁用":"启用"}}</el-button>
                <el-button type="text" @click="del(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="el-margin-t-10 my-el-pagination"
            @current-change="currentChangeHandle"
            :current-page="table.currentPage"
            :page-size="table.pageSize"
            layout="total, prev, pager, next, jumper"
            :total="table.rowCount"
          ></el-pagination>
        </el-row>
        <ou-editor v-show="dtype!=='list'" :dtype="dtype" @rePrev="rePrev" :ruleForm="curRow"></ou-editor>
      </el-row>
    </el-row>
  </div>
</template>
<script>
import { bus } from "../../tools/bus";
import { setItem, getItem, download } from "../../tools/common";
import ouEditor from "./addOrEdit.vue";
import axios from "axios";
export default {
  components: {
    ouEditor
  },
  data() {
    return {
      buildNum: "",
      unitNum: "",
      houseNum: "",
      isAuth: "",
      houseTypes: ["商品住宅", "还建房", "经济适用房"],
      dtype: "list",
      curRow: {},
      table: {
        tableData: [],
        currentPage: 1,
        pageSize: 10,
        rowCount: 3,
        queryKey: ""
      }
    };
  },
  mounted() {
    this.getMessage();
  },
  methods: {
    search() {
      this.table.currentPage = 1;
      this.getMessage();
    },
    routeTo(type, rows) {
      let self = this;
      let info = getItem("info") ? getItem("info") : {};
      self.dtype = type;
      self.curRow = rows
        ? rows
        : {
            communityId: info.communityId,
            houseId: "",
            buildNum: "",
            unitNum: "",
            houseNum: "",
            saleArea: "",
            realArea: "",
            houseType: "",
            isAuth: "",
            usable: "",
            createTime: ""
          };
    },
    getMessage() {
      let url = "/house/list";
      let info = getItem("info") ? getItem("info") : {};
      let p = {
        communityId: info.communityId,
        start: (this.table.currentPage - 1) * this.table.pageSize,
        num: this.table.pageSize
      };

      if (this.buildNum) p.buildNum = this.buildNum;
      if (this.unitNum) p.unitNum = this.unitNum;
      if (this.houseNum) p.houseNum = this.houseNum;
      if (this.isAuth) p.isAuth = this.isAuth;

      this.$http
        .fetch(url, p)
        .then(res => {
          console.log(res);
          this.table.rowCount = res.data.total;
          this.table.tableData = [];
          for (let i = 0; i < res.data.rows.length; i++) {
            let row = res.data.rows[i];
            this.table.tableData.push({
              communityId: info.communityId,
              houseId: row.houseId ? row.houseId : "",
              buildNum: row.buildNum ? row.buildNum : "",
              unitNum: row.unitNum ? row.unitNum : "",
              houseNum: row.houseNum ? row.houseNum : "",
              saleArea: row.saleArea ? row.saleArea : "",
              realArea: row.realArea ? row.realArea : "",
              houseType: row.houseType ? row.houseType : "",
              isAuth: row.isAuth ? row.isAuth : "",
              usable: row.usable ? row.usable : "",
              createTime: row.createTime ? row.createTime : ""
            });
          }
        })
        .catch(err => {});
    },
    currentChangeHandle(pageNum) {
      this.table.currentPage = pageNum;
      this.getMessage();
    },
    setUsable(rows) {
      this.$confirm(
        "确定" +
          (rows.usable ? "禁用" : "启用") +
          "房号为" +
          rows.houseNum +
          "的房屋？",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          let url = "/house/" + (rows.usable ? "disable" : "usable");
          let p = {
            houseId: rows.houseId
          };

          this.$http
            .fetch(url, p)
            .then(res => {
              this.getMessage();
            })
            .catch(err => {});
        })
        .catch(() => {});
    },
    del(rows) {
      this.$confirm("确定删除房号为" + rows.houseNum + "的房屋？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let url = "/house/delete";
          let p = {
            houseId: rows.houseId
          };

          this.$http
            .fetch(url, p)
            .then(res => {
              if (
                this.table.tableData.length == 1 &&
                this.table.currentPage > 1
              ) {
                this.table.currentPage -= 1;
              }
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getMessage();
            })
            .catch(err => {});
        })
        .catch(() => {});
    },
    upload(event) {
      let param = new FormData(); //创建form对象
      let info = getItem("info") ? getItem("info") : {};
      param.append("file", event.target.files[0]); //通过append向form对象添加数据
      param.append("communityId", info.communityId);
      let base = this.$myUrl.apiUrl() + "/house/excelImport";
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: sessionStorage.token
        }
      };
      axios
        .post(base, param, config)
        .then(res => {

          if (res.data.code == 0) {
            this.$message({
              type: "success",
              message: res.data.msg
            });
          } else {
            this.$message({
              type: "error",
              message: res.data.msg
            });
          }
            this.$refs.referenceUpload.value = null;
        })
        .catch(() => {
          this.$refs.referenceUpload.value = null;
        });
    },
    download() {
      let base = this.$myUrl.apiUrl();
      let token = sessionStorage.token;
      let url = `${base}/house/excelImportTemplate?Authorization=${token}`;
      console.log(token);
      window.location.href = url;
    },
    rePrev(isUpdate) {
      this.dtype = "list";
      if (isUpdate) {
        this.getMessage();
      }
    }
  }
};
</script>
